// Package controllerCategory
// @Description:分类控制器
package controllerCategory

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"go-member/controller/common"
	"go-member/db"
	"go-member/model"
	"go-member/tool"
	"go-member/validata"
	"strconv"
)

// CategoryList
// @Description: 分类列表
// @return gin.HandlerFunc
func CategoryList() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		mysql := db.InitMysql()
		defer mysql.Close()
		page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
		var count uint
		category := new([]model.Category)
		mysql.Model(&category).Debug().Count(&count)
		pageSize, _ := strconv.Atoi(tool.GetEnvDefault("web-category-page-size", "10"))
		mysql.Limit(pageSize).Offset((page - 1) * pageSize).Order("id DESC").Debug().Find(category)
		dataStruct := model.CategoryStruct{}
		dataStruct.List = category
		dataStruct.Total = count
		dataStruct.CurrentPage = uint(page)
		common.Success(ctx, "success", dataStruct)
	}
}

// AddCategory
// @Description: 添加分类
// @return gin.HandlerFunc
func AddCategory() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		check := validata.Check(ctx, validata.AddCategory())
		if check != nil {
			common.ErrorBadRequest(ctx, check)
			return
		}
		money := ctx.PostForm("money")
		number := ctx.PostForm("number")
		numberInt, _ := strconv.Atoi(number)
		note := ctx.PostForm("note")
		category := model.Category{}
		mysql := db.InitMysql()
		defer mysql.Close()
		err := mysql.Debug().Where("money=?", money).Where("number=?", number).First(&category).Error
		if err != gorm.ErrRecordNotFound {
			common.ErrorBadRequest(ctx, "相同金钱与次数的分类已存在")
			return
		}
		addUser := model.AddCategory{
			Money:      money,
			Number:     uint(numberInt),
			Note:       note,
			Created_at: tool.Now(),
			Updated_at: tool.Now(),
		}

		tx := mysql.Begin()
		addErr := tx.Table("category").Debug().Create(&addUser).Error
		if addErr != nil {
			tx.Callback()
			common.Error(ctx, "添加失败")
			return
		}
		tx.Commit()
		common.Success(ctx, "添加成功", addUser)
	}
}
